﻿using System;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using ASBCC.Business;
using ASBCC.Business.CCS;
using ASBCC.Database.Service;
using ASPNET.StarterKit.IssueTracker.BusinessLogicLayer;
using Microsoft.VisualBasic.CompilerServices;
using System.Security.Authentication;


namespace BEGDC.CC.Web
{
    /// <summary>
    /// Summary description for Global.
    /// </summary>
    public class Global : System.Web.HttpApplication
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        public Global()
        {
            InitializeComponent();

            this.Error += new EventHandler(Global_Error);
            this.AuthorizeRequest += new EventHandler(Global_AuthorizeRequest);
        }

        /// <summary>
        /// occur when asp.net exception throws
        /// </summary>
        void Global_Error(object sender, EventArgs e)
        {
            bool enableExceptionCatch;
            try
            {
                string exceptionConfig = System.Configuration.ConfigurationSettings.AppSettings["CatchException"];
                enableExceptionCatch = Convert.ToBoolean(exceptionConfig);
                if (!enableExceptionCatch)
                    return;


                HttpContext ctx = HttpContext.Current;
                Exception exception = ctx.Server.GetLastError();

                CSPrincipal principle = ctx.User as CSPrincipal;
                if (principle != null)
                    GlobalHelper.PutExceptionLog(exception, principle.CIL);
                else
                    GlobalHelper.PutExceptionLog(exception, null);


                this.Server.ClearError();
                if (exception is AuthenticationException || exception.InnerException is AuthenticationException)
                {
                    GlobalHelper.LogOperation(this.User.Identity.Name, SystemModule.Admin, "用户:" + this.User.Identity.Name + " 试图越权访问'" + HttpContext.Current.Request.Url.PathAndQuery + "'页面");
                    this.Response.Redirect("~/error/AccessDenied.html");
                }
                else
                    this.Response.Redirect("~/error/Error.html");
            }
            catch
            {
            }
        }

        /// <summary>
        /// occur when authorize request
        /// </summary>
        void Global_AuthorizeRequest(object sender, EventArgs e)
        {


            if (this.Request.IsAuthenticated &&
                this.Request.AppRelativeCurrentExecutionFilePath.ToLower().Contains(".aspx"))
            {
                // after this , get Role2s from "(this.User as CSPrincipal).Role2s" which contains RoleIDs split with ";"
                InitPrincipal();
            }

        }

        protected void Application_Start(Object sender, EventArgs e)
        {
            try
            {
                System.Data.SqlClient.SqlDependency.Start(DatabaseManager.ConnectionString);

            }
            catch (Exception exw)
            {
                ;
            }

        }

        protected void Session_End(Object sender, EventArgs e)
        {

        }

        protected void Application_End(Object sender, EventArgs e)
        {
            System.Data.SqlClient.SqlDependency.Stop(DatabaseManager.ConnectionString);
        }

        /// <summary>
        /// Initial CSPrincipal which is inherited from CCPrincipal contain Role2s
        /// since this.Request.IsAuthenticated must true and cookies is injected
        /// so we can get roles from cookie rather than from database
        /// </summary>
        private void InitPrincipal()
        {
            if (this.Context.Request.Cookies["useroles"] == null) throw new Exception("Cookie 'useroles' mustn't be null");
            string[] userolesData = FormsAuthentication.Decrypt(this.Context.Request.Cookies["useroles"].Value).UserData.Split(';');
            this.Context.User = new CSPrincipal(this.User.Identity, userolesData, this.Request.AppRelativeCurrentExecutionFilePath.ToLower());
        }

        #region Web Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
        }
        #endregion

    }
}

